<?php
/**
 * 标签
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-06-01
 * @author chenyan
 */

class tagModel extends model
{
	public function get_tag_id_by_tag($tag){
		$tag = trim($tag);
		if(empty($tag)){
			return 0;
		}
		$row = DB::fetchOne('SELECT tag_id FROM '.DB::table('tag').' WHERE tag = "'.DB::escape_string($tag).'"');
		return intval($row['tag_id']);
	}
	public function add($tag){
		$tag_id = $this->get_tag_id_by_tag($tag);
		if($tag_id == 0){
			$tag_id = DB::insert('tag', array('tag' => $tag, 'tag_count' => 0));
		}
		return $tag_id;
	}
	public function update($model_id, $tags){
		$tag_arr = explode(',', $tags);
		$has_tag_arr = DB::fetchArray('SELECT tag,tag_model_id FROM '.DB::table('tag').' as a, '.DB::table('tag_model').' as b WHERE a.tag_id = b.tag_id AND b.model_id = '.$model_id);
		foreach($has_tag_arr as $key => $item){
			foreach($tag_arr as $k => $i){
				if($item == $i){
					unset($has_tag_arr[$key]);
					unset($tag_arr[$k]);
					break;
				}
			}
		}
		$tag_ids = array();
		foreach($has_tag_arr as $i){
			$tag_ids[] = $i['tag_model_id'];
		}
		if(count($tag_ids)>0){
			DB::delete('tag_model', 'tag_model_id IN ('.implode(',', $tag_ids).')');
		}
		$sql_items = array();
		foreach($tag_arr as $i){
			$sql_items[] = '('.$this->add($i).", {$model_id})";
		}
		if(count($sql_items)>0){
			$sql = 'INSERT INTO '.DB::table('tag_model').' (tag_id, model_id) VALUES ';
			$sql .= implode(',', $sql_items);
		}
		DB::query($sql);
		return;
	}
	public function search($tag){
		$tag_id = $this->get_tag_id_by_tag($tag);
		if($tag_id == 0){
			return array();
		}
		return DB::fetchArray('SELECT * FROM '.DB::table('tag_model').' as a, '.DB::table('model').' as b WHERE a.tag_id = '.$tag_id.' AND a.model_id = b.model_id');
	}
	public function get_tags_by_model_id($model_id){
		return DB::fetchArray('SELECT * FROM '.DB::table('tag_model').' as a, '.DB::table('model').' as b WHERE a.model_id = '.$model_id.' AND a.model_id = b.model_id');
	}
}
?>